<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Chart_model extends CI_Model{
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Options - start time on chart
     * @return int
     */
    public function opt_start_time() {
        $formdate = empty($_GET['formdate']) ? false : my_check_date($_GET['formdate']);
        if ($formdate === false) {
            $period = (0 == $this->opt_period()) ? 1 : $this->opt_period();
            if (0 == $this->opt_period() || isset($_GET['submitperiod'])) {
                $res = mktime(date('H'), date('i'), date('s'), date('m'), ( date('d') - $period), date('Y'));
            } else {
                $res = mktime(0, 0, 0, date('m'), date('d') - $period, date('Y')); //*/
            }
        } else {
            $date_elements = explode(".", strip_quotes($_GET['formdate']));
            $res = mktime(0, 0, 0, $date_elements[1], $date_elements[0], $date_elements[2]);
        }
        return $res;
    }
    
    /**
     * Options - end time on chart
     * @return int
     */
    public function opt_end_time() {
        $graph_period = $this->opt_period();
        if (0 == $graph_period) $graph_period = 1;
        return mktime(date("H", $this->opt_start_time()), date("i", $this->opt_start_time()), date("s", $this->opt_start_time()), date("m", $this->opt_start_time()), (date("d", $this->opt_start_time()) + $graph_period), date("Y", $this->opt_start_time()));
    }
    
    /**
     * Options - title on chart
     * @param int $time_zone
     * @return string
     */
    public function opt_title_date($path) {
        date_default_timezone_set("UTC");
        $time_zone = $this->tree_model->get_time_zone_from_path($path);
        $tz = $time_zone * 3600;

        if (date('d', $this->opt_start_time()) == '01' && $this->opt_period() == $this->get_lastday_of_month($this->opt_start_time())) {
            $res = strftime("[%B %Y]", $this->opt_start_time());
        } elseif (date('His', $this->opt_start_time()) != '000000') {
            $res = strftime("[%d.%m.%Y %H:%M - ", $this->opt_start_time() + $tz) . strftime("%d.%m.%Y %H:%M]", $this->opt_end_time() + $tz);
        } elseif ($this->opt_period() == '1') {
            $res = strftime("[%d.%m.%Y - %A]", $this->opt_start_time());
        } else {
            $res = strftime("[%d.%m.%Y - ", $this->opt_start_time()) . strftime("%d.%m.%Y]", $this->opt_end_time() - 1);
        }
        date_default_timezone_set("Europe/Moscow");
        return $res;
    }
    
    /**
     * Option width on chart
     * @return int
     */
    public function opt_width() {
        if (!empty($_GET['formwidth'])) {
            $res = preg_match("/^\d{1,4}$/", $_GET['formwidth']) ? my_digit_only($_GET['formwidth']) : $this->settings->get_chart_width();
            $res = $res < $this->config->item('min_chart_width') ? $this->config->item('min_chart_width') : $res;
        }else
            $res = $this->settings->get_chart_width();
        return $res;
    }

    /**
     * Option height on chart
     * @return int
     */
    public function opt_height() {
        if (!empty($_GET['formheight'])) {
            $res = preg_match("/^\d{1,4}$/", $_GET['formheight']) ? my_digit_only($_GET['formheight']) : $this->settings->get_chart_height();
            $res = $res < $this->config->item('min_chart_height') ? $this->config->item('min_chart_height') : $res;
        }else
            $res = $this->settings->get_chart_height();
        return $res;
    }
    
    /**
     * Option X-Grid
     * @param boolean $is_prev This is preview?
     * @return string 
     */
    public function opt_x_grid($is_prev=FALSE){
        return $this->settings->get_chart_xgrid_param($this->opt_period(),$is_prev);
    }

    /**
     * Option period on chart
     * @return int
     */
    public function opt_period() {
        $formperiod = (empty($_GET['formperiod']))?0:strip_quotes($_GET['formperiod']);

        if ($formperiod === 'month') {
            $tms = empty($_GET['formdate']) ? time() : $this->graph_opt('starttime');
            $res = (isset($_GET['prevmonth'])) ? $this->get_lastday_of_prev_month($tms) : $this->get_lastday_of_month($tms);
        } elseif (my_digit_only($formperiod) > 0) {
            $res = $formperiod;
        } else {
            $res = 0;
        }
        return my_digit_only($res);
    }
    
    /**
     * режим отображения графиков
     * @return string
     */
    public function opt_mode(){
        $upper_limit = isset($_GET['formmaxoy']) && my_check_digit($_GET['formmaxoy'])?" --rigid --upper-limit ".my_digit_only($_GET['formmaxoy']):"";      //лимит по оси Y
        return $upper_limit." --interlaced".$this->settings->get_chart_mode();
    }
    
    /**
     * префикс файла за предыдущие месяцы в формате = date("Y.m-")
     * @return string
     */
    public function opt_date_graph() {
        if (!(date("Y.m", $this->opt_start_time()) == date("Y.m") || mktime() - $this->opt_start_time() < 2764800))
            $res = date("Y.m-", $this->opt_start_time());
        else
            $res = "";
        return $res;
    }
    
    /**
     * Получить последний день текущего месяца (кол-во дней в месяце)
     * @param int $timestamp
     * @return int
     */
    private function get_lastday_of_month($timestamp){
        $lastday = date('t',$timestamp);
        return $lastday;
    }
    /**
     * Получить последний день предыдущего месяца (кол-во дней в месяце)
     * @param int $timestamp
     * @return int
     */
    private function get_lastday_of_prev_month($timestamp){
        $lastday = date('t',$timestamp - (86400 * get_lastday_of_month($timestamp)));
        return $lastday;
    }
    
    /**
     * Проверяем наличие desc файла с описанием
     * @param BynaryNode $node
     * @return boolean|string Если файл найден возвращаем содержимое, иначе FALSE
     */
    public function get_description($node){
        $path = str_replace(".sh", ".desc", $node->get_path());
        if (file_exists($path)) {
            return file_get_contents($path);
        }else{
//            return "ntrnc <b>dfdf</b> ddfgdg";
            return FALSE;
        }
    }
    
    
}